package zpx.service;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.compass.core.util.StringUtils;
import org.springframework.stereotype.Service;

import zpx.idao.IUserDao;
import zpx.iservice.IComAttachmentService;
import zpx.iservice.IUserService;
import zpx.model.Pager;
import zpx.model.User;
import zpx.model.UserException;


@Service("userService")
public class UserService implements IUserService {

	private IUserDao userDao;
	
	public IUserDao getUserDao() {
		return userDao;
	}	
	@Resource
	public void setUserDao(IUserDao userDao) {
		this.userDao = userDao;
	}
	

	private IComAttachmentService comAttachmentService;

	public IComAttachmentService getComAttachmentService() {
		return comAttachmentService;
	}
	
	@Resource
	public void setComAttachmentService(IComAttachmentService comAttachmentService) {
		this.comAttachmentService = comAttachmentService;
	}
	
	@Override
	public void add(User user) {
		User u = userDao.loadByUsername(user.getUsername());
		if(u!=null) throw new UserException("瑕佹坊鍔犵殑鐢ㄦ埛宸茬粡瀛樺�?");
		userDao.add(user);
	}

	@Override
	public void update(User user) {
		userDao.update(user);
	}

	@Override
	public void delete(String id) {
		userDao.delete(id);
	}

	@Override
	public User load(String id) {
		return userDao.load(id);
	}

	@Override
	public List<User> list() {
		return userDao.list();
	}
	
	@Override
	public List<User> getUserList(Map<String, String> searchMap){
		return userDao.getUserList(searchMap);
	}
	
	@Override
	public int getUserCount() {
		return userDao.getUserCount();
	}


	@Override
	public User login(String username, String password) {
		User u = userDao.loadByUsername(username);
		if(u==null) throw new UserException("用户不存在");
		if(!u.getPassword().equals(password)) throw new UserException("密码不对");
		return u;
	}

	@Override
	public void saveUpdate(Map<String, Object> searchMap) {
		User user=(User) searchMap.get("user");
		if(StringUtils.hasText(user.getId())){
		user.setUpdateDate(new Date());
		userDao.update(user);
	}else {
		user.setPermission("2");
		user.setCreateDate(new Date());
		userDao.add(user);
	}
		String fileNames=(String) searchMap.get("fileNames");
		String filePaths=(String) searchMap.get("filePaths");
		String delComAttIds=(String) searchMap.get("delComAttIds");
		User loginUser=(User) searchMap.get("loginUser");
		// 保存附件
        if (fileNames != null && !"".equals(fileNames.trim()) && filePaths != null
                && !"".equals(filePaths.trim())) {
        	comAttachmentService.saveComAttachment(fileNames, filePaths,
                    user.getId(),loginUser);
        }
        // 删除附件
        if (delComAttIds != null && !"".equals(delComAttIds.trim())) {
        	comAttachmentService.deleteComAttachments(delComAttIds,loginUser);
        }
		
	}

}
